<template>
	<view class="update-password-page">
		<!-- 页面头部 -->
		<view class="page-header">
			<view class="header-content">
				<text class="page-title">🔒 修改密码</text>
				<text class="page-subtitle">保障账户安全</text>
			</view>
		</view>

		<!-- 密码修改表单 -->
		<view class="form-container">
			<view class="form-card">
				<view class="form-header">
					<text class="form-title">设置新密码</text>
					<text class="form-desc">请输入当前密码和新密码</text>
				</view>

				<!-- 表单字段 -->
				<view class="form-content">
					<!-- 原密码 -->
					<view class="form-item">
						<view class="item-label">
							<text class="label-icon">🔑</text>
							<text class="label-text">原密码</text>
						</view>
						<view class="input-wrapper">
							<input 
								class="form-input"
								type="password" 
								v-model="oldPassword" 
								placeholder="请输入当前密码"
								maxlength="20"
								@focus="onInputFocus('old')"
								@blur="onInputBlur('old')"
							/>
						</view>
						<view v-if="errors.oldPassword" class="error-message">
							<text class="error-text">{{ errors.oldPassword }}</text>
						</view>
					</view>

					<!-- 新密码 -->
					<view class="form-item">
						<view class="item-label">
							<text class="label-icon">🆕</text>
							<text class="label-text">新密码</text>
						</view>
						<view class="input-wrapper">
							<input 
								class="form-input"
								type="password" 
								v-model="newPassword" 
								placeholder="请输入新密码（6-20位）"
								maxlength="20"
								@input="validateNewPassword"
								@focus="onInputFocus('new')"
								@blur="onInputBlur('new')"
							/>
						</view>
						<view v-if="errors.newPassword" class="error-message">
							<text class="error-text">{{ errors.newPassword }}</text>
						</view>
						<!-- 密码强度指示器 -->
						<view v-if="newPassword" class="password-strength">
							<view class="strength-label">密码强度：</view>
							<view class="strength-indicator">
								<view 
									v-for="(level, index) in 4" 
									:key="index"
									class="strength-bar"
									:class="{
										'weak': passwordStrength >= 1 && index === 0,
										'medium': passwordStrength >= 2 && index <= 1,
										'strong': passwordStrength >= 3 && index <= 2,
										'very-strong': passwordStrength >= 4 && index <= 3
									}"
								></view>
							</view>
							<text class="strength-text">{{ passwordStrengthText }}</text>
						</view>
					</view>

					<!-- 确认密码 -->
					<view class="form-item">
						<view class="item-label">
							<text class="label-icon">✓</text>
							<text class="label-text">确认密码</text>
						</view>
						<view class="input-wrapper">
							<input 
								class="form-input"
								type="password" 
								v-model="confirmPassword" 
								placeholder="请再次输入新密码"
								maxlength="20"
								@input="validateConfirmPassword"
								@focus="onInputFocus('confirm')"
								@blur="onInputBlur('confirm')"
							/>
						</view>
						<view v-if="errors.confirmPassword" class="error-message">
							<text class="error-text">{{ errors.confirmPassword }}</text>
						</view>
						<view v-else-if="confirmPassword && confirmPassword === newPassword" class="success-message">
							<text class="success-text">✓ 密码一致</text>
						</view>
					</view>
				</view>

				<!-- 密码规则提示 -->
				<view class="password-rules">
					<text class="rules-title">密码要求：</text>
					<view class="rules-list">
						<text class="rule-item">• 6-20个字符</text>
						<text class="rule-item">• 建议包含字母、数字和特殊字符</text>
						<text class="rule-item">• 不能与原密码相同</text>
					</view>
				</view>

				<!-- 提交按钮 -->
				<view class="form-actions">
					<button 
						class="submit-btn"
						:class="{ 'disabled': !isFormValid || isSubmitting }"
						:disabled="!isFormValid || isSubmitting"
						@click="update"
					>
						<LoadingSpinner v-if="isSubmitting" :size="'small'" color="#ffffff" />
						<text v-else class="btn-text">确认修改</text>
					</button>
					<button class="cancel-btn" @click="goBack">
						<text class="btn-text">取消</text>
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { request } from '@/request/index.js'
	import LoadingSpinner from '@/components/common/LoadingSpinner.vue'
	
	export default {
		name: 'UpdatePasswordPage',
		components: {
			LoadingSpinner
		},
		data() {
			return {
				// 密码字段
				oldPassword: '',
				newPassword: '',
				confirmPassword: '',
				
				// 用户信息
				username: '',
				
				// UI状态
				isSubmitting: false,
				
				// 验证错误
				errors: {
					oldPassword: '',
					newPassword: '',
					confirmPassword: ''
				},
				
				// 输入框焦点状态
				focusStates: {
					old: false,
					new: false,
					confirm: false
				}
			}
		},
		computed: {
			// 密码强度计算
			passwordStrength() {
				if (!this.newPassword) return 0
				
				let strength = 0
				// 长度检查
				if (this.newPassword.length >= 6) strength++
				// 包含小写字母
				if (/[a-z]/.test(this.newPassword)) strength++
				// 包含大写字母或数字
				if (/[A-Z0-9]/.test(this.newPassword)) strength++
				// 包含特殊字符
				if (/[^a-zA-Z0-9]/.test(this.newPassword)) strength++
				
				return strength
			},
			
			// 密码强度文本
			passwordStrengthText() {
				switch (this.passwordStrength) {
					case 0: return ''
					case 1: return '弱'
					case 2: return '一般'
					case 3: return '强'
					case 4: return '非常强'
					default: return ''
				}
			},
			
			// 表单验证状态
			isFormValid() {
				return this.oldPassword.length > 0 &&
					   this.newPassword.length >= 6 &&
					   this.confirmPassword === this.newPassword &&
					   this.oldPassword !== this.newPassword &&
					   !this.errors.oldPassword &&
					   !this.errors.newPassword &&
					   !this.errors.confirmPassword
			}
		},
		onLoad() {
			const userInfo = uni.getStorageSync('user')
			if (!userInfo || userInfo === 'null' || userInfo === '') {
				uni.showToast({
					title: '请先登录',
					success() {
						uni.reLaunch({
							url: '/pages/login/login'
						})
					}
				})
				return
			}
			
			if (userInfo.user && userInfo.user.login_id) {
				this.username = userInfo.user.login_id
			} else {
				uni.showToast({
					title: '用户信息异常',
					icon: 'none'
				})
			}
		},
		methods: {
			// 输入框焦点事件
			onInputFocus(type) {
				this.focusStates[type] = true
				this.clearError(type)
			},
			
			// 输入框失焦事件
			onInputBlur(type) {
				this.focusStates[type] = false
				if (type === 'old') {
					this.validateOldPassword()
				} else if (type === 'new') {
					this.validateNewPassword()
				} else if (type === 'confirm') {
					this.validateConfirmPassword()
				}
			},
			
			// 清除错误信息
			clearError(type) {
				if (type === 'old') {
					this.errors.oldPassword = ''
				} else if (type === 'new') {
					this.errors.newPassword = ''
				} else if (type === 'confirm') {
					this.errors.confirmPassword = ''
				}
			},
			
			// 验证原密码
			validateOldPassword() {
				if (!this.oldPassword) {
					this.errors.oldPassword = '请输入原密码'
					return false
				}
				if (this.oldPassword.length < 6) {
					this.errors.oldPassword = '密码长度不能少于6位'
					return false
				}
				this.errors.oldPassword = ''
				return true
			},
			
			// 验证新密码
			validateNewPassword() {
				if (!this.newPassword) {
					this.errors.newPassword = '请输入新密码'
					return false
				}
				if (this.newPassword.length < 6) {
					this.errors.newPassword = '密码长度不能少于6位'
					return false
				}
				if (this.newPassword.length > 20) {
					this.errors.newPassword = '密码长度不能超过20位'
					return false
				}
				if (this.oldPassword && this.newPassword === this.oldPassword) {
					this.errors.newPassword = '新密码不能与原密码相同'
					return false
				}
				this.errors.newPassword = ''
				return true
			},
			
			// 验证确认密码
			validateConfirmPassword() {
				if (!this.confirmPassword) {
					this.errors.confirmPassword = '请确认新密码'
					return false
				}
				if (this.confirmPassword !== this.newPassword) {
					this.errors.confirmPassword = '两次输入的密码不一致'
					return false
				}
				this.errors.confirmPassword = ''
				return true
			},
			
			// 返回上一页
			goBack() {
				uni.navigateBack({
					delta: 1
				})
			},
			
			// 提交密码修改
			async update() {
				// 防止重复提交
				if (this.isSubmitting) return
				
				// 验证所有字段
				const isOldValid = this.validateOldPassword()
				const isNewValid = this.validateNewPassword()
				const isConfirmValid = this.validateConfirmPassword()
				
				if (!isOldValid || !isNewValid || !isConfirmValid) {
					uni.showToast({
						title: '请检查输入信息',
						icon: 'none'
					})
					return
				}
				
				// 二次确认
				const confirmed = await this.showConfirmModal()
				if (!confirmed) return
				
				try {
					this.isSubmitting = true
					
					const data = {
						username: this.username,
						oldPwd: this.oldPassword,
						newPwd: this.newPassword
					}
					
					const response = await request({
						url: '/thirdUpdatePwd',
						method: 'POST',
						data: data,
						header: {
							'Content-Type': 'application/x-www-form-urlencoded',
							'cookie': uni.getStorageSync('cookie')
						}
					})
					
					if (response.data.code === '200') {
						// 清除用户信息
						uni.removeStorageSync('user')
						uni.removeStorageSync('cookie')
						
						uni.showModal({
							title: '修改成功',
							content: '密码修改成功，请使用新密码重新登录',
							showCancel: false,
							confirmText: '去登录',
							success: () => {
								uni.reLaunch({
									url: '/pages/login/login'
								})
							}
						})
					} else {
						uni.showToast({
							title: response.data.msg || '修改失败',
							icon: 'none',
							duration: 3000
						})
						
						// 如果是原密码错误，清空原密码输入框
						if (response.data.msg && response.data.msg.includes('原密码')) {
							this.oldPassword = ''
							this.errors.oldPassword = response.data.msg
						}
					}
				} catch (error) {
					console.error('修改密码失败:', error)
					uni.showToast({
						title: '网络错误，请稍后重试',
						icon: 'none'
					})
				} finally {
					this.isSubmitting = false
				}
			},
			
			// 显示确认对话框
			showConfirmModal() {
				return new Promise((resolve) => {
					uni.showModal({
						title: '确认修改',
						content: '确定要修改密码吗？修改后需要重新登录。',
						confirmText: '确认修改',
						cancelText: '取消',
						success: (res) => {
							resolve(res.confirm)
						},
						fail: () => {
							resolve(false)
						}
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
@import '@/styles/variables.scss';

.update-password-page {
	min-height: 100vh;
	padding: $spacing-lg;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.page-header {
	margin-bottom: $spacing-xl;
	
	.header-content {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: $spacing-sm;
		padding: $spacing-lg 0;
	}
	
	.page-title {
		font-size: $font-size-xxl;
		font-weight: 700;
		color: $text-white;
		text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
	}
	
	.page-subtitle {
		font-size: $font-size-base;
		color: rgba(255, 255, 255, 0.8);
		text-align: center;
	}
}

.form-container {
	display: flex;
	justify-content: center;
}

.form-card {
	width: 100%;
	max-width: 600rpx;
	background: $white;
	border-radius: $border-radius-xl;
	padding: $spacing-xl;
	box-shadow: $shadow-xl;
	position: relative;
	overflow: hidden;
	
	&::before {
		content: '';
		position: absolute;
		top: 0;
		left: 0;
		right: 0;
		height: 8rpx;
		background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
	}
}

.form-header {
	text-align: center;
	margin-bottom: $spacing-xl;
	padding-top: $spacing-md;
	
	.form-title {
		font-size: $font-size-xl;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: $spacing-sm;
		display: block;
	}
	
	.form-desc {
		font-size: $font-size-sm;
		color: $text-secondary;
		line-height: 1.5;
		display: block;
	}
}

.form-content {
	display: flex;
	flex-direction: column;
	gap: $spacing-xl;
}

.form-item {
	display: flex;
	flex-direction: column;
	gap: $spacing-sm;
}

.item-label {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	margin-bottom: $spacing-xs;
	
	.label-icon {
		font-size: $font-size-base;
		color: $primary-color;
	}
	
	.label-text {
		font-size: $font-size-base;
		font-weight: 500;
		color: $text-primary;
	}
}

.input-wrapper {
	position: relative;
	display: flex;
	align-items: center;
}

.form-input {
	flex: 1;
	height: 88rpx;
	padding: 0 $spacing-md;
	border: 2px solid $border-color;
	border-radius: $border-radius-base;
	font-size: $font-size-base;
	color: $text-primary;
	background: $white;
	transition: all 0.3s ease;
	
	&:focus {
		border-color: $primary-color;
		outline: none;
		box-shadow: 0 0 0 4rpx rgba(24, 144, 255, 0.1);
	}
	
	&::placeholder {
		color: $text-placeholder;
		font-size: $font-size-sm;
	}
}

.error-message {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	padding: $spacing-xs $spacing-sm;
	background: lighten($error-color, 45%);
	border: 1px solid lighten($error-color, 30%);
	border-radius: $border-radius-sm;
	
	.error-text {
		font-size: $font-size-xs;
		color: $error-color;
		font-weight: 500;
	}
}

.success-message {
	display: flex;
	align-items: center;
	gap: $spacing-xs;
	padding: $spacing-xs $spacing-sm;
	background: lighten($success-color, 45%);
	border: 1px solid lighten($success-color, 30%);
	border-radius: $border-radius-sm;
	
	.success-text {
		font-size: $font-size-xs;
		color: $success-color;
		font-weight: 500;
	}
}

.password-strength {
	display: flex;
	align-items: center;
	gap: $spacing-md;
	padding: $spacing-sm 0;
	
	.strength-label {
		font-size: $font-size-xs;
		color: $text-secondary;
		font-weight: 500;
		min-width: 120rpx;
	}
	
	.strength-indicator {
		display: flex;
		gap: $spacing-xs;
		flex: 1;
	}
	
	.strength-bar {
		height: 8rpx;
		flex: 1;
		background: $gray-200;
		border-radius: $border-radius-sm;
		transition: all 0.3s ease;
		
		&.weak {
			background: #ff4d4f;
		}
		
		&.medium {
			background: #faad14;
		}
		
		&.strong {
			background: #52c41a;
		}
		
		&.very-strong {
			background: #1890ff;
		}
	}
	
	.strength-text {
		font-size: $font-size-xs;
		font-weight: 600;
		min-width: 80rpx;
		text-align: right;
		
		&:empty {
			display: none;
		}
	}
}

.password-rules {
	padding: $spacing-lg;
	background: $gray-50;
	border-radius: $border-radius-base;
	border-left: 4px solid $info-color;
	margin: $spacing-lg 0;
	
	.rules-title {
		font-size: $font-size-sm;
		font-weight: 600;
		color: $text-primary;
		margin-bottom: $spacing-sm;
		display: block;
	}
	
	.rules-list {
		display: flex;
		flex-direction: column;
		gap: $spacing-xs;
	}
	
	.rule-item {
		font-size: $font-size-xs;
		color: $text-secondary;
		line-height: 1.4;
	}
}

.form-actions {
	display: flex;
	flex-direction: column;
	gap: $spacing-md;
	margin-top: $spacing-xl;
}

.submit-btn {
	height: 88rpx;
	border-radius: $border-radius-base;
	background: linear-gradient(135deg, $primary-color 0%, darken($primary-color, 10%) 100%);
	color: $text-white;
	font-size: $font-size-base;
	font-weight: 600;
	border: none;
	box-shadow: $shadow-md;
	transition: all 0.3s ease;
	display: flex;
	align-items: center;
	justify-content: center;
	gap: $spacing-sm;
	
	&:not(.disabled):active {
		transform: translateY(2rpx);
		box-shadow: $shadow-sm;
	}
	
	&.disabled {
		background: $gray-300;
		color: $text-disabled;
		box-shadow: none;
		cursor: not-allowed;
	}
	
	.btn-text {
		font-size: $font-size-base;
		font-weight: 600;
	}
}

.cancel-btn {
	height: 88rpx;
	border-radius: $border-radius-base;
	background: $white;
	color: $text-secondary;
	font-size: $font-size-base;
	font-weight: 500;
	border: 2px solid $border-color;
	transition: all 0.3s ease;
	display: flex;
	align-items: center;
	justify-content: center;
	
	&:active {
		background: $gray-50;
		border-color: $primary-color;
		color: $primary-color;
	}
	
	.btn-text {
		font-size: $font-size-base;
		font-weight: 500;
	}
}

// 响应式设计
@media (max-width: 750rpx) {
	.update-password-page {
		padding: $spacing-md;
	}
	
	.form-card {
		padding: $spacing-lg;
	}
	
	.form-header {
		margin-bottom: $spacing-lg;
	}
	
	.form-content {
		gap: $spacing-lg;
	}
	
	.password-strength {
		flex-direction: column;
		align-items: flex-start;
		gap: $spacing-sm;
		
		.strength-label {
			min-width: auto;
		}
		
		.strength-indicator {
			width: 100%;
		}
	}
}
</style>